const app = getApp();
Page({
    data: {
        config: app.config,

        cont: "", //备注
        checked:false,
        latitude: '',
        longitude: '',
        startTimer: '',
        endTimer: '',
        idSta: true,
        firstClick: 0,
        idGoPop: false,
        beFromNum:'',

        promotionType: 0, // 商品类型\
		strEmail: ''
    },
    onLoad(query) {
      my.setNavigationBar({
        reset: true,
      });

      app._init_(this)
      
      const data = JSON.parse(query.data);
	  
	  console.log(data)
	  
      if (data.match.value == 1) {
          data.detail += data.match.tit.name
      }

      data.staShow = data.detail.substring(0,4);


      // // 期数
      // data.period = parseInt(data.leaseTerm/2592000000);
	  // if(data.smash.value )
      let totalPrice = data.money
      let leaseTerm = data.leaseTerm;
      if (data.trem_value ==365){
          leaseTerm = 12
      } else if (data.trem_value == 180){
          leaseTerm = 6
      }else if(data.trem_value==90){
          leaseTerm = 3
      } else if (data.trem_value==30){
          // leaseTerm = 1
		  leaseTerm =30
      } else if (data.trem_value==14){
          leaseTerm = 14
      } else if (data.trem_value==24){
          leaseTerm = 24
      }
      data.saleQuantity = data.saleQuantity ? data.saleQuantity : 1;
      console.log(110,data.saleQuantity )
      // console.log("sadfasfadsfas->", data)
      // console.log(totalPrice+"--------"+leaseTerm)
      // // 首期租金
      let yu = totalPrice % leaseTerm
      let meiqiPrice = (totalPrice - yu) / leaseTerm
      data.firstRent =  ((((yu + meiqiPrice) /  100).toFixed(2))*data.saleQuantity).toFixed(2);

	  
      // 活动显示价格
      let activePrice = (totalPrice - 1) / (leaseTerm-1);
	  console.log(activePrice)
      // 活动剩余租金
      data.activeLastRent = (activePrice / 100).toFixed(2);
	  
      data.leaseTerm = leaseTerm

      data.dayRent = (data.money / data.trem_value / 100).toFixed(2)
      //   剩余租金
      data.lastRent = (((meiqiPrice / 100).toFixed(2))*data.saleQuantity).toFixed(2)
	  if (leaseTerm == 30 || leaseTerm == 14 || leaseTerm == 24 ) {
	  		  // data.firstRent = data.smash.value /  100;
	  		 data.lastRent = (((totalPrice) / (leaseTerm) / 100).toFixed(2)*data.saleQuantity).toFixed(2)
	  }
      data.image = data.slideshows[0];
	  let endAllDay = (data.trem_value - 0) * 86400;
	  if (data.trem_value == 14 || data.trem_value == 24 ) {
		  endAllDay = (data.trem_value * 7 - 0) * 86400;
	  }

      // // 总租金
      // data.allRent = this._floatMu(data.selectPrice.price,data.selectNum*data.period);
      // // 总押金
      // data.allDeposit = app.fenToYuan(data.product.deposit*data.selectNum);
      // // console.log("data.product.deposit",data.product.deposit)
      // // 完结价
      // data.buyoutPrice = app.fenToYuan(data.product.priceall*data.selectNum);
      this.setData(data);

      this.getTime(endAllDay);

      this.getBeFrom();

      this.getIdCardUrl();

        // 获当前地址
      app.getLocation()

    },

    // 获取来自
    getBeFrom(){
      let beFromNum = app.globalData.query.beFromNum;
      if(beFromNum){
        this.setData({
          beFromNum: beFromNum
        });
      }
    },

    selectChecked(){
        this.setData({
            checked:!this.data.checked
        })
    },

    // 获取时间
    getTime(timer){
      let date = new Date();

      let y = date.getFullYear();
      let m = date.getMonth() + 1;
      m = m < 10 ? "0" + m : m;
      let d = date.getDate();
      d = d < 10 ? "0" + d : d;
      let start = y + '.' + m + '.' + d;
      let startTim = y + '-' + m + '-' + d;
      // let end = (y - 0 + 1) + '.' + m + '.' + d;
      this.setData({
        startTimer : start
      })

      let t = new Date().getTime()/1000;
      let timNum = Math.floor(t);

      if(timer){
        let endNum = timNum + timer;
        let endTime = new Date(endNum*1000);
        let endy = endTime.getFullYear();
        let endm = endTime.getMonth() + 1;
        endm = endm < 10 ? "0" + endm : endm;
        let endd = endTime.getDate();
        endd = endd < 10 ? "0" + endd : endd;
        let end = endy + '.' + endm + '.' + endd;

        this.setData({
          endTimer : end
        })
      }
    },
	// 电子邮箱
	getEmail (e) {
		this.setData({ strEmail: e.detail.value });
	},
    // 备注
    onNote(e) {
        this.setData({ cont: e.detail.value });
    },
    // 选择地址
    onAddressSet() {
      if(this.data.btn) {return false}
      this.setData({btn:true})
      my.getAddress({
          success: (res) => {
              this.setData({
                  btn: false,
                  tit: res.result.fullname,   // 姓名
                  province: res.result.prov,   // 省
                  city: res.result.city,        //市
                  district: res.result.area,   // 区
                  street: res.result.street,   //路
                  address: res.result.address, //地址
                  phone: res.result.mobilePhone, //电话
              });
              my.hideLoading();
          },
          fail:()=>{
              this.setData({
                  btn: false
              })
              my.hideLoading();
          }
      });
    },
    colseAddress(){
        this.setData({
            tit: null,   // 姓名
            province:null,   // 省
            city: null,        //市
            district: null,   // 区
            street: null,   //路
            address: null, //地址
            phone: null, //电话
        });
    },

    // 租赁协议
    zulin(){
        let data = new Date()
        data = data.getFullYear() + '年' + (data.getMonth()+1) + '月' + data.getDate()+'日'
        let item = {
            createtime:data,  // 时间
            leaseTerm:Math.floor(this.data.trem_value/30),// 租期
            allRent:this.data.buyOut/100 , // 总租金
            tit:this.data.tit , //
            phone:this.data.phone,
            shopsVo: this.data.shops,
            userVo: my.getStorageSync({ key: 'user' }).data,
            province: this.data.province,
            city: this.data.city,
            district: this.data.district,
            address: this.data.address,
            testOrder: this.data.testOrder,
            params:{
                // 商品基础数据
                title: this.data.msg,
                id: this.data.id,
                skuId: this.data.skuId,
                version: this.data.version,
                clipCoupons: this.data.clipCoupons ? this.data.clipCoupons : 0,
                model: {
                    price: this.data.money,
                    leaseTerm: this.data.trem_value,
                },
                saleQuantity: this.data.saleQuantity,

                deposit: this.data.cash,
                buyOutPrice: this.data.buyOut,
                purchasePrice: this.data.purchase,
                image: this.data.image,
                detail: this.data.detail,
                smash: this.data.smash.value
            }
        }
        
        my.navigateTo({
            url: `/pages/user/agreementList/agreementList?param=${encodeURIComponent(JSON.stringify(item))}`
        })
    },

    // 提交下单经纬度
    upLocationFun(){
      let user = my.getStorageSync({ key: 'user' });
      let id = user.data.id;
      let globalData = app.globalData;
      // console.log(globalData, '获取信息');

      if(globalData.longitude && globalData.latitude){
        // console.log(globalData.longitude,globalData.latitude,'查看位置333333333333');

        let dataObj = {
          id: id,
          latitude: globalData.latitude,
          longitude: globalData.longitude
        }

        app.user.upLngLat(dataObj)
          .then((res=>{
            // console.log(res,'提交经纬度')
          }))


      }else{
        // app.getLocation();
      }


    },

     // fromId
    onSubmitfromId(e){

        this.upLocationFun();

        // console.log("e======>>>>", e)
        // console.log("fromId======>>>>", e.detail.formId)
        this.setData({
            formId:e.detail.formId
        })
    },
    getPhoneNumber(){
        // this.onSubmit()
        // return
        // 没有手机号
        let that = this
        let user = my.getStorageSync({ key: 'user' });
        // console.log(user,'获取用户信息')
        let phone = user.data.phone ? user.data.phone : null
        // console.log("===========手机号============", phone)
        if (phone == null) {
            my.getPhoneNumber({
                success: (res) => {
                    // console.log("=============支付宝返回==============", res)
                    let encryptedData = res.response;
                    let data = {
                        encryptedData: encryptedData
                    }
                    app.user.setPhoneNum(data)
                    .then((json=>{
                        // console.log("=============后端返回==============", json)
                        if (json.code == 200) {
                            user.data.phone = json.data
                            // 保存到缓存中
                            my.setStorage({
                                key: 'user',
                                data: user.data,
                            })
                            that.onSubmit()
                        } else {
                            that.onSubmit()
                        }
                    }))
                    .catch((err)=>{
                       that.onSubmit();
                    })
                },
                fail: (res) => {
                  that.onSubmit()
                    // console.log("================支付宝返回2====================", res);
                    // console.log('getPhoneNumber_fail');
                },
            });
        } else {
            that.onSubmit()
        }
    },
    //提交数据
    onSubmit() {
		let reg = /^[a-zA-Z0-9]+([-_.][A-Za-zd]+)*@([a-zA-Z0-9]+[-.])+[A-Za-zd]{2,5}$/
		if (!reg.test(this.data.strEmail)){
			my.showToast({ content: "请填写正确的邮箱地址" });
			return;
		}
        my.showLoading({
          content: '加载中...',
        });


        if (!this.data.tit) {
            this.onAddressSet();
            return;
        }

        // if(this.data.address.length > 25){
        //   my.showToast({content: '请修改详细地址，长度不能超过25'});
        //   return;
        // }
		

        let num = this.data.firstClick;
        if(!this.data.idSta && this.data.firstClick == 0){
          num += 1;
          this.setData({
            idGoPop: true,
            firstClick: num
          })
          my.hideLoading();
          return;
        }
        // 订单数据详细数据
        const data = Object.assign(
            {},
            // this.accectData,
            {
                // 商品基础数据
                title: this.data.msg,
                id: this.data.id,
                skuId: this.data.skuId,
                version: this.data.version,
                clipCoupons: this.data.clipCoupons ? this.data.clipCoupons : 0,
                model: {
                    price: this.data.money,
                    leaseTerm: this.data.trem_value,
                },
                deposit: this.data.cash,
                buyOutPrice: this.data.buyOut,
                purchasePrice: this.data.purchase,
                numberDevices: this.data.saleQuantity,

                image: this.data.image,
                detail: this.data.detail,
                smash: this.data.smash.value
            }
        );

        let  params = {
            isAgreement: 0,
            agreementNo: null,

            testOrder: this.data.testOrder,

            params: JSON.stringify(data),

            tit: this.data.tit,
            province: this.data.province,
            city: this.data.city,
            district: this.data.district,
            street: this.data.street,
            address: this.data.address,
            phone: this.data.phone,

            invoice: this.data.invoice,
            cont: this.data.cont,
            sid: this.data.sid,
            orderAuthCode:this.data.formId,
            currentAddress:app.globalData.userlocation,
            channelType: this.data.beFromNum,
			email: this.data.strEmail
        }

        my.getAuthCode({
          scopes: 'order_service',
          success: (res) => {
            
          },
          complete: (res) => {
            console.log('创建订单',params)
            app.order.save(params)
            .then(json=>{
                console.log(7777, json)
                if(json.code!=200) {
                    my.alert({
                        content:json.msg
                    });
                    return
                }
                setTimeout(() => {
                  my.reLaunch({ url: "/pages/order/renzheng/renzheng?id=" + json.data });
                }, 500)
            })
            .catch((err)=>{
              my.hideLoading();
              my.showToast({
                content: err.msg
              })
            })
            
          }
        });

        
    },

     // 跳转
    navigateTo(e){
        app.navigateTo(e)
    },

    // 弹窗去上传身份跳转
    goIdPage(e){
      this.setData({
        idGoPop: false
      })
      app.navigateTo(e);
    },

    // 关闭弹窗
    closeIdPop(){
      this.setData({
        idGoPop: false
      })
    },


    // 跳转
    getIdCardUrl(){
      let userData = my.getStorageSync({ key: 'user' });
      let sta = true;
      if(userData.data.idCardUrl){
        sta = true;
      }else{
        sta = false;
      }
      this.setData({
        idSta: sta
      })
    }


});
